<?php
/**
 * @package Sj Mega News
 * @version 2.5
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @copyright (c) 2012 YouTech Company. All Rights Reserved.
 * @author YouTech Company http://www.smartaddons.com
 * 
 */
defined('_JEXEC') or die;

class MegaNewsReader extends SjReader{		
	public function getList(&$params){			
		$items =array();
			$arrcustom_url=array();
			$arrcustom_url = $this->_getCustomUrl($params['custom_url']);				
			$user 		=&	JFactory::getUser();
			$app 		=&	JFactory::getApplication();
			$db   		=&	JFactory::getDBO();
			$jnow		=& 	JFactory::getDate();
			$now		= 	$jnow->toMySQL();
			$nullDate	=	$db->getNullDate();
			$noauth		= !	$app->getParams()->get('show_noauth');
			$aid = $user->get ( 'aid', 0 );
			$aid = 1;
		
			if (!isset($params['source']) || empty($params['source'])){
				$this->errors = "No selected or all selected is unpublished.";
			return array();
			} 
			$arraycatid = ($params['source']);    
			if (!is_null ($arraycatid)){
				if (!is_array($arraycatid)) {
					$arraycatid = array($arraycatid);
				}
                foreach ($arraycatid as $key=> $value) {
					$query = 'SELECT a.*,u.name as creater,cc.id as catid, cc.description as catdesc, cc.title as cattitle, cc.access as cat_access, ' . ' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,' . ' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug FROM #__content AS a' . ' INNER JOIN #__categories AS cc ON cc.id = a.catid' . ' left JOIN #__users AS u ON a.created_by = u.id';          
					$query .= ' WHERE a.state = 1 '. ($noauth ? ' AND a.access <= ' . ( int ) $aid . ' AND cc.access <= ' . ( int ) $aid : '') . ' AND (a.publish_up = ' . $db->Quote ( $nullDate ) . ' OR a.publish_up <= ' . $db->Quote ( $now ) . ' ) ' . ' AND cc.id = '."{$value}".' AND (a.publish_down = ' . $db->Quote ( $nullDate ) . ' OR a.publish_down >= ' . $db->Quote ( $now ) . ' )' . ' AND cc.published = 1';
					if ($params['featured'] == 0) {
						$query .= ' AND a.featured = 0';
					} else if ($params['featured'] == 1) {
						$query .= ' AND a.featured = 1';
					}
				    switch ($params['sort_order_field']){
                    	case 'created': $ordering = 'a.created DESC';
                        	break;                
                        case 'modified': $ordering = 'a.modified DESC';                            
                        	break; 
                        case 'ordering': $ordering = 'a.ordering';                            
                        	break;    
                        case 'title': $ordering = 'a.title';                            
                        	break;              
                        case 'mostpopular': $ordering = 'a.hits DESC';
                        	break;                
                        case 'leastpopular': $ordering = 'a.hits ASC';                            
                        	break;               
                        case 'random': $ordering = 'RAND()';
                        	break;                          
                        default:       $ordering = 'a.created';                              
                        	break;
					}              
					$query .=  ' ORDER BY ' . $ordering;            
					$query .=  $params['total'] ? ' LIMIT ' . $params['total'] : '';					   
					$db->setQuery($query);
					$a = $db->loadObjectlist();					
					
					if(!empty($a)){
                    	$items[$value] = $a;
					}
					
				}
			}
					$imgResizeConfig = array(
			    		'background' => $params['item_thumbnail_background'],
				    	'thumbnail_mode' => $params['item_thumbnail_mode']);							
					YTools::getImageResizerHelper($imgResizeConfig);
					include_once JPATH_SITE . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php';
                    if(!is_null($items)){							
                    foreach ($items as $key=>$value){                  			
				    	$article = array();
				      	foreach ($value as $item) {
							$temp = array();	
							if($item->cat_access <= $aid ) {
								$item->category_link = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catslug));
							}
							if (!isset($item->category_sub_title)){
								$item->category_sub_title = YTools::truncate($item->cattitle,$params['limit_title_category']);
							}
							$item->introtext = trim($item->introtext);
							$item->text = $item->introtext;
							$item->article_image[0] =json_decode($item->images)->image_intro;
							if ('none' == $params['item_thumbnail_mode']){					
								$item->image = (empty( $item->article_image) || !file_exists($item->article_image[0]) ) ? 'modules/mod_sj_meganews/assets/images/nophoto.gif' : $item->article_image[0]  ;
							} else {
								$item->image=  (empty( $item->article_image) || !file_exists($item->article_image[0]) ) ? 'modules/mod_sj_meganews/assets/images/nophoto.gif' : $item->article_image[0];
								if (false != $item->image && !YTools::isUrl($item->image)){
									$item->image = YTools::resize($item->image, $params['item_thumbnail_width'], $params['item_thumbnail_height'], $params['item_thumbnail_mode']);
								}					
							}	
						    if($item->access <= $aid ) {
		                        if(array_key_exists($item->id, $arrcustom_url)){
									$item->article_link = $arrcustom_url[$item->id];
								}else{
									$item->article_link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
								}
							}						
							$item->article_sub_title = YTools::truncate($item->title, $params['limit_title_article']);
							$item->article_content = YTools::truncate($item->text,$params['limit_description']);
							if ($params['description_keephtml'] == 0){
								$item->article_content = strip_tags($item->article_content);
							}	
						    $temp['article_id'] = $item->id;
						    $temp['category_link'] = $item->category_link;					
							$temp['category_sub_title']= $item->category_sub_title;				   
						    $temp['article_sub_title'] = $item->article_sub_title;		
						    $temp['article_link'] = $item->article_link;	 
							$temp['creater'] = $item->creater;
						    $temp['article_image'] = $item->image;						
							$temp['article_content'] = $item->article_content;     				   					 							
							$article[] = $temp;
						}
						$items[$key] =$article;
					}
			}
    	return $items;      
	}
	private function _getCustomUrl($custom_url) {     
    	$arrUrl = array();
        $tmp = explode("\n", trim($custom_url));            
        foreach( $tmp as $strTmp){
        	$pos = strpos($strTmp, ":");
            if($pos >=0){
            	$tmpKey = substr($strTmp, 0, $pos);
                $key = trim($tmpKey);
                $tmpLink = substr($strTmp, $pos+1, strlen($strTmp)-$pos);
                $haveHttp =  strpos(trim($tmpLink), "http://");
                //var_dump($haveHttp);die;                   
                if($haveHttp<0 || ($haveHttp !== false) ){
                    $link = trim($tmpLink);
                }else{
                    $link = "http://" . trim($tmpLink);
                }
                $arrUrl[$key] = $link;
            }  
        }            
        return $arrUrl;
	}
}